import argparse
import urllib.request
import urllib.parse
from sys import argv

import json

admin_token = "vHjntkWUrmi5agpDCZV7"
base_url = 'http://gitlab.corp.hongen.com/api/v4'
headers = {'Private-Token': admin_token}


def get(url):
    request_obj = urllib.request.Request(url, None, headers)
    response = urllib.request.urlopen(request_obj)
    content_b = response.read()
    return content_b.decode('utf-8')


def post(url, data):
    data = urllib.parse.urlencode(data)
    data = data.encode('utf-8')
    url = urllib.request.Request(url, data, headers)
    response = urllib.request.urlopen(url)
    content_b = response.read()
    return content_b.decode('utf-8')


def get_all(sub_url):
    string = get(base_url + sub_url)
    objs = json.loads(string)
    for obj in objs:
        print(obj['id'], obj['name'])


def set_project_var(project_id, var_map):
    url = base_url + "/projects/" + project_id + "/variables"
    data = {'key': var_map.split('=')[0], 'value': var_map.split('=')[1], 'id': project_id}
    print(headers, post(url, data))


def main():
    # set_project_var("33", "k=v")
    if len(argv) < 3:
        print("usage:gitlab.py get/set/delete project/group/user")
        return
    if argv[1] == 'get':
        if argv[2] == 'groups' or argv[2] == 'projects' or argv[2] == 'users':
            get_all("/" + argv[2])

    if argv[1] == 'set':
        if argv[2] == 'project':
            if int(argv[3]) > 0 and argv[4] == '-v' and argv[5]:
                set_project_var(argv[3], argv[5])


if __name__ == '__main__':
    main()
